<!--
 * @Author: ckk
 * @Date: 2022-08-29 11:17:06
 * @LastEditors: ckk
 * @LastEditTime: 2022-08-30 15:52:08
 * @Description: 课本选择
-->
<template>
  <div class="home flexBox">
    <div class="version-head">
      <div class="ver-head">
        <yj-mob-icon name="arrow-left" color="rgba(0,0,0,0.65)" size="17px" @click="goback()"/>
        <div @click="openGrade" class="checkedGrede">
          <span>{{activeGredeName}} {{activeTrimName}}</span>
          <yj-mob-icon name="arrow-down" color="rgba(0,0,0,0.5)" />
        </div>
      </div>
      <p class="ver-title"><span>课本选择</span></p>
    </div>
    <div class="version-content">
      <div class="ver-item" v-for="(item, index) in versionArr" :key="index" @click="checkBook(item.boId)" :style="{marginRight:(index+1)%3==0?'0px':'5%'}">
        <div :class="activeBook == item.boId ? 'ver-img ver-item-active' : 'ver-img'">
          <img class="ver-bg" :src="ImgUrl(item.boId)" alt="" />
          <img v-show="activeBook == item.boId" class="ver-checked" src="../../assets/images/circle.svg" alt="" />
        </div>
        <p>{{item.enumName}}</p>
      </div>
    </div>
    <button class="save-btn" @click="saveBookVersion()">保存</button>
    <!-- 展示切换年级 -->
    <yj-mob-popup
      v-model="show"
      round
      closeable
      close-icon-position="top-right"
      position="bottom"
      :style="{ minHeight: '30%' }">
      <div class="grade">
        <div class="headline">选择年级学期</div>
        <div class="check-grade">
          <div class="check-name">
            <div class="check-title">
              <span>选择年级</span>
              <span class="line"></span>
            </div>
          </div>
          <div class="check-content">
            <div
              :class="activeGrede == item.gradeCode ? 'check-one checked' : 'check-one'"
              v-for="(item, index) in gradeList"
              :key="index"
              @click="checkGrade(item.gradeCode,item.gradeName)">
              {{ item.gradeName }}
            </div>
          </div>
        </div>
        <div class="check-grade">
          <div class="check-name">
            <div class="check-title">
              <span>选择学期</span>
              <span class="line"></span>
            </div>
          </div>
          <div class="check-content">
            <div
              :class="activeTrim == item.termCode ? 'check-one checked' : 'check-one'"
              v-for="(item, index) in tremList"
              :key="index"
              @click="checkTrim(item.termCode, item.termName )">
              <span>{{ item.termName }}</span>
            </div>
          </div>
        </div>
        <button class="save-btn" @click="saveCheckGrade()">确定</button>
      </div>
    </yj-mob-popup>
  </div>
</template>

<script>
import { Popup, Icon } from 'yj-mob-ui';
// editBookVersion
import { getGradeList, getBookImage, editBookVersion } from '../../api/getSynchronizationApi';
import { setStudentCode } from '../../api/getContentApi';
import { getJsonlocalStore } from '../../common/comfun';
import { excellentServices } from '@/api';
import local from '@/utils/local.js';
export default {
  components: {
    [Popup.name]: Popup,
    [Icon.name]: Icon
  },
  data () {
    return {
      activeBook: '',
      show: false,
      gradeList: [],
      tremList: [],
      syncCatalogList: [],
      studentStageCode: '',
      activeGrede: '',
      activeGredeName: '',
      checkGredeName: '',
      activeTrim: '',
      activeTrimName: '',
      checkTrimName: '',
      versionArr: [],
      versionImage: [],
      userInitInfo: {},
      currentInfo: {
        currentStageCode: '', // 当前学段编码
        currentGradeCode: '', // 当前年级编码
        currentTermCode: '', // 当前学期编码
        currentSubjectCode: '' // 当前学科编码
      }
    };
  },
  async created () {
    await this.getVersion();
    const userInitInfo = getJsonlocalStore('userInitInfo');
    if (userInitInfo) {
      this.userInitInfo = userInitInfo;
      this.activeTrim = userInitInfo.termCode;
      this.activeTrimName = userInitInfo.termName;
      this.checkGredeName = this.activeGredeName;
      this.checkTrimName = this.activeTrimName;
      this.tremList = userInitInfo.eduTermList;
      this.studentStageCode = userInitInfo.studentStageCode;
      const gradeData = await getGradeList(),
        newDatas = gradeData.data.filter(
          (item) => item.stageCode === userInitInfo.studentStageCode
        );
      this.activeGrede = userInitInfo.gradeCode;
      this.gradeList = newDatas.length > 0 ? newDatas[0].gradeList : [];
      this.activeGredeName = this.gradeList.filter(item => item.gradeCode === this.activeGrede)[0].gradeName;
    }
  },
  methods: {
    async saveBookVersion () {
      const query = {
        studyStageCode: this.studentStageCode,
        gradeCode: this.activeGrede,
        termCode: this.activeTrim,
        subjectCode: localStorage.getItem('currentSubjectCode'),
        bookId: this.activeBook
      },
      editBookRes = await editBookVersion(query);
      if (editBookRes) {
       this.$router.push({ name: 'home' });
      }
    },
    /**
     * @description: 获取书本的版本
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-30 10:09:15
     * @return {*}
     */
    async getVersion () {
      const version = JSON.parse(local.get('version'));
      if (version) {
      this.versionArr = version.versionArr || [];
      this.activeBook = version.activeVersion;
      const newArr = [];
      this.versionArr.forEach(item => {
        newArr.push(item.boId);
      });
        const verImgRes = await getBookImage({ codes: newArr.join(',') });
        if (verImgRes.code === 0) {
          this.versionImage = verImgRes.data;
        }
    }
    },
    /**
     * @description: 获取课程
     * @param {*} getBookIdFlag
     * @Author: ckk
     * @Date: 2022-08-30 10:08:44
     * @return {*}
     */
    async getCourseData (getBookIdFlag) {
      const userInitInfo = getJsonlocalStore('userInitInfo');
      this.currentInfo = {
        currentStageCode: userInitInfo.studentStageCode, // 当前学段编码
        currentGradeCode: this.activeGrede, // 当前年级编码
        currentTermCode: this.activeTrim, // 当前学期编码
        currentSubjectCode: localStorage.getItem('currentSubjectCode') // 当前学科编码
      };
      // 获取当前选择的版本
      if (!getBookIdFlag) {
        const param = {
          studyStageCode: this.currentInfo.currentStageCode,
          gradeCode: this.currentInfo.currentGradeCode,
          subjectCode: this.currentInfo.currentSubjectCode
        };
        if (this.currentInfo.currentStageCode !== '0003') {
          param.termCode = this.currentInfo.currentTermCode;
        }
        const bookRecord = await excellentServices.studentGetBookId(param);
        try {
          this.bookId = bookRecord.data.bookId;
        } catch (error) {
        }
      }
      const that = this,
        tagstr = that.currentInfo.currentStageCode === '0003' ? `section-0003,subject-${that.currentInfo.currentSubjectCode}` : `section-${that.currentInfo.currentStageCode},grade-${that.currentInfo.currentGradeCode},volume-${that.currentInfo.currentTermCode},subject-${that.currentInfo.currentSubjectCode}`,
        params = { tags: tagstr, pageNum: 1, pageSize: 100, status: 1 },
        res = await excellentServices.getCrouseList(params); // /catalogue/list_course
        that.syncCatalogList = res.data.syncList || [];
        this.getCourseReady = true;
      // 如果有同步课程
      if (that.syncCatalogList.length > 0) {
        // 获取所有的版本信息 用于切换信息
        const versionArr = that.stuHomeEdiFormat(that.syncCatalogList, []),
          versionObj = {};
          // 12.23 libaochuan
        // 根据获取的 进度里面的bookId 定位当前版本
          // 根据获取的 进度里面的bookId 定位当前版本
        let parentId = '',
          childId = '',
          prevBookObj = versionArr.find(item => {
            // 根第一层id 匹配到 说明只有一层版本
            if (item.itemCode === this.bookId) {
              parentId = item.itemCode;
              childId = this.bookId;
              return true;
            }
            // 如果存在二级版本的时候，则说明根据 获取用户保存的版本 与 第二层版本匹配，
            if (item.childList) {
              let flag = false;
              item.childList.some(innerItem => {
                if (innerItem.itemCode === this.bookId) {
                  parentId = item.itemCode;
                  childId = this.bookId;
                  flag = true;
                  return true;
                }
              });
              return flag;
            }
          });
        if (!prevBookObj) {
          prevBookObj = versionArr[0];
          versionObj.versionArr = versionArr;
          versionObj.activeVersion = prevBookObj.itemCode;
          versionObj.semester = prevBookObj.childList ? prevBookObj.childList[0].itemCode : '';
          if (versionObj.semester) {
            this.bookId = versionObj.semester;
          } else {
            this.bookId = versionObj.activeVersion;
          }
          local.set('version', JSON.stringify(versionObj));
        } else {
          versionObj.versionArr = versionArr;
          versionObj.activeVersion = parentId;
          versionObj.semester = prevBookObj.childList ? childId : '';
          local.set('version', JSON.stringify(versionObj));
        }
      }
      this.getVersion();
    },
    stuHomeEdiFormat (course = [], arr = []) {
      const taget = [];
      course.forEach(item => {
        item.tags && item.tags.forEach(v => {
          if (v.tagId === 'edition') {
            const obj = Object.assign({}, v, { tags: item.tags });
            obj.fileUrl = item.fileUrl;
            obj.boId = item.id;
            taget.push(obj);
          }
        });
      });
      const arys = [];
      taget.forEach(item => {
        if (!arys.includes(item.enumCode)) {
          arr.push(item);
        } else {
          const num = arr.findIndex(h => h.enumCode === item.enumCode);
          arr[num].tags = arr[num].tags.concat(item.tags);
        }
        arys.push(item.enumCode);
      });
      arr.forEach(item => {
        item.tags.forEach(v => {
          if (v.tagId === 'electivetype') {
            if (item.childList) {
              item.childList.push(v);
            } else {
              item.childList = [v];
            }
          }
        });
      });
      return arr;
    },
    /**
     * @description: 保存选择的年级
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-29 17:31:04
     * @return {*}
     */
    async saveCheckGrade () {
      const query = {
        gradeCode: this.activeGrede,
        studyStageCode: this.userInitInfo.studentStageCode,
        subjectCode: localStorage.getItem('currentSubjectCode'),
        termCode: this.activeTrim
      },
      res1 = await setStudentCode({ ...query });
      if (res1.code === '200') {
        this.userInitInfo.currentTermCode = this.activeTrim;
        this.userInitInfo.gradeCode = this.activeGrede;
        this.userInitInfo.termName = this.checkTrimName;
        this.activeGredeName = this.checkGredeName;
        this.activeTrimName = this.checkTrimName;
        localStorage.setItem('userInitInfo', JSON.stringify(this.userInitInfo));
        this.getCourseData();
        this.show = false;
      }
    },
    /**
     * @description: 选择版本
     * @param {*} id
     * @Author: ckk
     * @Date: 2022-08-29 17:04:55
     * @return {*}
     */
    checkBook (id) {
      this.activeBook = id;
    },
    /**
     * @description: 返回上一页
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-29 17:03:25
     * @return {*}
     */
    goback () {
      this.$router.go(-1);
    },
    /**
     * @description: 处理img
     * @param {*} url
     * @Author: ckk
     * @Date: 2022-08-29 15:56:35
     * @return {*}
     */
    ImgUrl (id) {
      const imgList = this.versionImage.filter(item => item.id === id);
      if (imgList.length > 0) {
        return imgList[0].url;
      } else {
        return '';
      }
    },
    /**
     * @description: 打开弹框显示年级
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-29 11:38:59
     * @return {*}
     */
    openGrade () {
      this.show = true;
    },
    /**
     * @description: 选择年级
     * @param {*} value
     * @Author: ckk
     * @Date: 2022-08-26 14:16:32
     * @return {*}
     */
    checkGrade (value, name) {
      this.activeGrede = value;
      this.checkGredeName = name;
    },
    /**
     * @description: 选择上下学期
     * @param {*} value
     * @Author: ckk
     * @Date: 2022-08-26 16:58:43
     * @return {*}
     */
    checkTrim (value, name) {
      this.activeTrim = value;
      this.checkTrimName = name;
    }
  }
};
</script>
<style scoped lang="scss">
// 页面
.version-head {
  height: 60px;
  width: 100%;
  position: relative;
  .ver-head {
    position: absolute;
    left: 0;
    top: 0;
    height: 60px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    box-sizing: border-box;
    align-items: center;
  }
}
.ver-title {
  height: 60px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 500;
  color: #333333;
}
.checkedGrede {
  font-size: 12px;
  font-weight: 400;
  color: #666666;
  span {
    margin-right: 5px;
  }
}
.version-content {
  display: flex;
  padding: 0 29px;
  align-items: center;
  // justify-content: space-between;
  flex-wrap: wrap;
  .ver-item {
    flex-shrink: 0;
    width: 30%;
    border-radius: 8px;
    position: relative;
    margin-top: 18px;
    margin-right:5%;
    .ver-bg {
      width: 100%;
      height: 127px;
      border-radius: 8px;
      display: block;
    }
    .ver-checked {
      position: absolute;
      right: 0;
      top: 0;
      width: 30px;
      height: auto;
    }
    p {
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      text-align: center;
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      padding-top:6px;
    }
  }
  .ver-item-active {
    border: 4px solid #53c856;
    border-radius: 8px;
    box-sizing: border-box;
  }
}
// 选择年纪学期
.headline {
  font-size: 20px;
  font-weight: 500;
  color: #000000;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.check-name {
  display: flex;
  align-items: center;
  padding: 0 20px;
}
.check-title {
  width: auto;
  position: relative;
  span {
    font-size: 18px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.65);
    width: auto;
  }
  .line {
    height: 6px;
    background: #53c856;
    border-radius: 10px;
    display: block;
    width: 100%;
    opacity: 0.3;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: -1;
  }
}
.check-content {
  display: flex;
  flex-wrap: wrap;
  padding-left: 20px;
  padding-right: 7px;
  .check-one {
    width: 74px;
    height: 36px;
    flex-shrink: 0;
    background: #fff;
    border-radius: 36px;
    opacity: 1;
    font-size: 14px;
    font-weight: 400;
    color: #333333;
    margin-right: 13px;
    margin-top: 17px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .checked {
    color: #ffffff;
    background: #53c856;
  }
}
.save-btn {
  width: 90%;
  margin: 0 auto;
  height: 46px;
  background: #53c856;
  border-radius: 36px;
  border: 0;
  font-size: 18px;
  font-weight: 500;
  color: #ffffff;
  margin-top: 25px;
  margin-bottom: 21px;
  display: block;
}
</style>
